
package com.carsite.dao.hibernate;

import java.util.List;

import org.springframework.orm.ObjectRetrievalFailureException;

import com.carsite.dao.BranchDao;
import com.carsite.model.Branch;

public class BranchDaoHibernate extends BaseDaoHibernate implements BranchDao {

    /**
     * @see com.carsite.dao.BranchDao#getBranchs(com.carsite.model.Branch)
     */
    public List getBranchs(final Branch branch) {
        return getHibernateTemplate().find("from Branch");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.
        if (branch == null) {
            return getHibernateTemplate().find("from Branch");
        } else {
            // filter on properties set in the branch
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(branch).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Branch.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }*/
    }

    /**
     * @see com.carsite.dao.BranchDao#getBranch(Long branchId)
     */
    public Branch getBranch(final Long branchId) {
        Branch branch = (Branch) getHibernateTemplate().get(Branch.class, branchId);
        if (branch == null) {
            log.warn("uh oh, branch with branchId '" + branchId + "' not found...");
            throw new ObjectRetrievalFailureException(Branch.class, branchId);
        }

        return branch;
    }

    /**
     * @see com.carsite.dao.BranchDao#saveBranch(Branch branch)
     */    
    public void saveBranch(final Branch branch) {
        getHibernateTemplate().saveOrUpdate(branch);
    }

    /**
     * @see com.carsite.dao.BranchDao#removeBranch(Long branchId)
     */
    public void removeBranch(final Long branchId) {
        getHibernateTemplate().delete(getBranch(branchId));
    }

	public List getTopBranchs() {
		return getHibernateTemplate().find("from Branch where parentId is null order by branchId desc");
	}
}
